# -*- coding:utf-8 -*-
import websocket
import thread
import time, datetime
import subprocess
import json
from baidu_speech import AipSpeech


def on_message(ws, message):
    message_dict = json.loads(message)
    if message_dict.get('stock_move_done'):
        move_line_dict = message_dict.get('stock_move_done')
        product_name = move_line_dict.get('name').split(' ')[1]
        product_qty = move_line_dict.get('product_uom_qty')
        voice_text = u"产品%s入库%s"%(product_name, product_qty)
        APP_ID = '9872232'
        API_KEY = 'AhrNAw665Cjc5nKAI38LqwhF'
        SECRET_KEY = 'jxGYlRcfla0HnG0Im5QCzqEei2lnn10m'
        aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
        result = aipSpeech.synthesis(voice_text, 'zh', 1, {
            'vol': 5,
        })
        if not isinstance(result, dict):
            with open('auido.mp3', 'wb') as f:
                f.write(result)
            subprocess.Popen(['mpg123', '-q', 'auido.mp3']).wait()

def on_error(ws, error):
    print error

def on_close(ws):
    time.sleep(3)
    connect_server()

def on_open(ws):
    def run(*args):
        ws.send("listen move")
    thread.start_new_thread(run, ())

def connect_server():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://192.168.0.54:8899",
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()

if __name__ == "__main__":
    connect_server()